import {useState, useRef, useEffect} from 'react'
import {PlusOutlined} from '@ant-design/icons'
import dayjs from 'dayjs'
import moment from 'moment/moment'
import {
    Button,
    Col,
    Flex,
    Form,
    Input,
    Row,
    Select,
    Typography,
    DatePicker,
    Table,
    Alert,
    Modal,
    message
} from 'antd'
import ImageUpload from '../components/ImageUpload'
import Amap from '../components/Amap'
import {
    sellerIndustryList,
    sellerVerifyAdd,
    sellerVerifyEdit,
    sellerVerifyList
} from '../service/seller'
import {Link, useNavigate} from 'react-router-dom'

const {RangePicker} = DatePicker

export default function SellerVerify() {
    const navigator = useNavigate()
    // 用于重新渲染组件
    const [n, setN] = useState(0)
    // 创建表单的引用
    const formRef = useRef()
    // 保存表格中选中的项
    const [selectedRowKeys, setSelectedRowKeys] = useState([])
    // 表格中是否有选中
    const hasSelected = selectedRowKeys.length > 0
    // 保存选择的日期
    const [selectedDate, setSelectedDate] = useState(null)
    const [selectedDateString, setSelectedDateString] = useState(null)
    // 模态框
    const [isModalOpen, setIsModalOpen] = useState(false)
    // 保存图像上传
    const [imageUrl, setImageUrl] = useState()
    // 保存坐标值
    const [position, setPosition] = useState({
        longitude: 116.397428,
        latitude: 39.90923
    })
    // 保存总页码
    const [total, setTotal] = useState(0)
    // 当前页码
    const [pageNo, setPageNo] = useState(1)
    const [condition, setCondition] = useState({})
    // 商家类型列表
    const [industryList, setIndustryList] = useState([])
    // 保存新增时商家类型
    const [industryType, setIndustryType] = useState('')
    // 预设日期
    const rangePresets = [
        {
            label: '最近一周',
            value: [dayjs().add(-7, 'd'), dayjs()]
        },
        {
            label: '最近一个月',
            value: [dayjs().add(-30, 'd'), dayjs()]
        },
        {
            label: '最近三个月',
            value: [dayjs().add(-90, 'd'), dayjs()]
        }
    ]
    // 日期切换获取日期
    const onRangeChange = (dates, dateStrings) => {
        if (dates) {
            // console.log('From: ', dates[0], ', to: ', dates[1])
            // console.log('From: ', dateStrings[0], ', to: ', dateStrings[1])
            setSelectedDate(dates)
            setSelectedDateString(dateStrings)
            console.log(dateStrings)
        } else {
            setSelectedDate(null)
        }
    }
    // 重置日期
    const handleReset = () => {
        setSelectedDate(null)
    }
    // 保存商家列表
    const [sellerList, setSellerList] = useState([])
    // 根据状态码返回状态
    const getStatus = (status) => {
        switch (status) {
            case 1:
                return '待审核'
            case 2:
                return '审核通过'
            case 3:
                return '审核驳回'
            case 4:
                return '分配账号'
            case 5:
                return '账户禁用'
        }
    }

    useEffect(() => {
        ;(async () => {
            // 查询商家
            const res = await sellerVerifyList({...condition, pageNo: pageNo})
            setSellerList(res.data.objects)
            setTotal(res.data.total)
            console.log(res)
            // 查询行业类型
            const res2 = await sellerIndustryList()
            setIndustryList(res2.data)
            console.log(res2)
        })()
    }, [n])

    return (
        <>
            <Row className="info">
                <Col span={24}>
                    <Flex justify={'space-between'}>
                        <Typography.Title level={4}>信息管理</Typography.Title>
                        <Button
                            type="primary"
                            icon={<PlusOutlined/>}
                            // onClick={() => setIsModalOpen(true)}
                            onClick={() => navigator('/admin/seller/add')}
                        >
                            新增商家
                        </Button>
                    </Flex>
                </Col>
            </Row>
            <Row className="container">
                <Col span={24}>
                    <Form
                        layout="inline"
                        onFinish={async (values) => {
                            if (selectedDate) {
                                values.startingTime = selectedDateString[0] + ' 0:0:0'
                                values.endTime = selectedDateString[1] + ' 23:59:59'
                            }
                            console.log(values)
                            // 保存条件
                            setCondition(values)
                            const res = await sellerVerifyList(values)
                            console.log(res)
                            setTotal(res.data.total)
                            setSellerList(res.data.objects)
                        }}
                    >
                        <Form.Item label="商家名称：" name="businessName">
                            <Input/>
                        </Form.Item>
                        <Form.Item label="负责人联系方式：" name="businessHeadPhone">
                            <Input type="phone"/>
                        </Form.Item>
                        <Form.Item label="审核状态：" name="businessStatus">
                            <Select
                                placeholder="请选择状态"
                                style={{width: 120}}
                                options={[
                                    {value: '', label: '所有'},
                                    {
                                        value: '1',
                                        label: '待审核'
                                    },
                                    {
                                        value: '2',
                                        label: '审核通过'
                                    },
                                    {
                                        value: '3',
                                        label: '审核驳回'
                                    },
                                    {
                                        value: '4',
                                        label: '分配账号'
                                    },
                                    {
                                        value: '5',
                                        label: '账户禁用'
                                    }
                                ]}
                            />
                        </Form.Item>
                        <Form.Item label="申请日期">
                            <RangePicker
                                value={selectedDate}
                                presets={rangePresets}
                                onChange={onRangeChange}
                            />
                        </Form.Item>
                        <Form.Item>
                            <Button type="default" htmlType="reset" onClick={handleReset}>
                                重置
                            </Button>
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit">
                                查询
                            </Button>
                        </Form.Item>
                    </Form>
                </Col>
            </Row>
            <Row className="container">
                <Col span={24}>
                    <Typography.Paragraph style={{fontSize: 16}}>
                        商家列表
                    </Typography.Paragraph>
                    {hasSelected && (
                        <Alert
                            message={`已经选择 ${selectedRowKeys.length} 项`}
                            type="info"
                            showIcon
                        />
                    )}
                </Col>
                <Col span={24}>
                    <Table
                        pagination={{
                            total,
                            defaultCurrent: 1,
                            onChange: async (pageNo) => {
                                const res = await sellerVerifyList({pageNo})
                                setSellerList(res.data.objects)
                                setPageNo(pageNo)
                            }
                        }}
                        rowKey="id"
                        rowSelection={{
                            selectedRowKeys,
                            onChange: (newSelectedRowKeys) => {
                                console.log('selectedRowKeys changed: ', newSelectedRowKeys)
                                setSelectedRowKeys(newSelectedRowKeys)
                            }
                        }}
                        dataSource={sellerList}
                        columns={[
                            {
                                title: '编号',
                                dataIndex: 'id',
                                key: 'id'
                            },
                            {
                                title: '商家名称',
                                dataIndex: 'businessName',
                                key: 'businessName'
                            },
                            {
                                title: '营业执照',
                                dataIndex: 'businessLicense',
                                key: 'businessLicense',
                                render: (_, record) => {
                                    return (
                                        <img src={record.businessLicense} width="60" height="40"/>
                                    )
                                }
                            },
                            {
                                title: '负责人',
                                dataIndex: 'businessHeadName',
                                key: 'businessHeadName'
                            },
                            {
                                title: '联系电话',
                                dataIndex: 'businessHeadPhone',
                                key: 'businessHeadPhone'
                            },
                            {
                                title: '申请时间',
                                dataIndex: 'entryTime',
                                key: 'entryTime'
                            },
                            {
                                title: '审批状态',
                                dataIndex: 'businessStatus',
                                key: 'businessStatus',
                                render: (_, record) => getStatus(record.businessStatus)
                            },
                            {
                                title: '操作',
                                dataIndex: 'op',
                                key: 'op',
                                align: 'center',
                                render: (_, record) => {
                                    return (
                                        <span className="op">
                      <Link to={`/admin/seller/edit/${record.id}`}>审批</Link>
                                            {/* <a>审批</a> */}
                                            {/* <a
                        onClick={async () => {
                          const res = await sellerVerifyEdit({
                            businessStatus: 2,
                            id: record.id
                          })
                          if (res.code === '0') {
                            message.success('批准成功')
                            setN(n + 1)
                          }
                        }}
                      >
                        批准
                      </a>
                      <a
                        onClick={async () => {
                          const res = await sellerVerifyEdit({
                            businessStatus: 3,
                            id: record.id
                          })
                          if (res.code === '0') {
                            message.success('已经设置为拒绝通过')
                            setN(n + 1)
                          }
                        }}
                      >
                        拒绝
                      </a> */}
                    </span>
                                    )
                                }
                            }
                        ]}
                    />
                </Col>
            </Row>
            {/* 模态框 */}
            <Modal
                title="新增商家"
                open={isModalOpen}
                onOk={() => formRef.current.submit()}
                onCancel={() => setIsModalOpen(false)}
                maskClosable={false}
                width={700}
                destroyOnClose
            >
                <Form
                    onFinish={async (v) => {
                        v.businessLicense = imageUrl
                        v.businessStatus = 1
                        console.log(v)
                        const res = await sellerVerifyAdd(v)
                        console.log(res)
                        if (res.code === '0') {
                            // 关闭模态框
                            setIsModalOpen(false)
                            message.success('新增商家成功！')
                            setN(n + 1)
                        } else {
                            message.error('新增商家失败')
                        }
                    }}
                    layout="vertical"
                    ref={formRef}
                    // 当字段被删除时不保留字段值
                    preserve={false}
                >
                    <Row>
                        <Col span={12}>
                            <Form.Item
                                label="商家名称"
                                name="businessName"
                                rules={[
                                    {
                                        required: true,
                                        message: '商家名称不能为空'
                                    }
                                ]}
                            >
                                <Input placeholder="请输入商家名称"/>
                            </Form.Item>
                        </Col>
                        <Col span={11} offset={1}>
                            <Form.Item
                                label="行业类型"
                                name="industryType"
                                rules={[
                                    {
                                        required: true,
                                        message: '行业类型不能为空'
                                    }
                                ]}
                            >
                                <Select
                                    placeholder="请选择行业"
                                    // defaultValue="1"
                                    onChange={(value) => setIndustryType(value)}
                                    fieldNames={{
                                        value: 'id'
                                    }}
                                    options={industryList}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                label="负责人"
                                name="businessHeadName"
                                rules={[
                                    {
                                        required: true,
                                        message: '负责人不能为空'
                                    }
                                ]}
                            >
                                <Input placeholder="请输入负责人"/>
                            </Form.Item>
                        </Col>
                        <Col span={11} offset={1}>
                            <Form.Item
                                label="负责人电话"
                                name="businessHeadPhone"
                                rules={[
                                    {
                                        required: true,
                                        message: '电话号码不能为空'
                                    },
                                    {
                                        pattern: /^1[3-9]\d{9}$/,
                                        message: '请输入正确的手机号码'
                                    }
                                ]}
                            >
                                <Input placeholder="请输入负责人电话"/>
                            </Form.Item>
                        </Col>
                        <Col span={24}>
                            <Form.Item
                                label="商家地址"
                                name="companyAddress"
                                rules={[
                                    {
                                        required: true,
                                        message: '电话号码不能为空'
                                    }
                                ]}
                            >
                                <Input/>
                                {/* <div
                  style={{
                    width: '100%',
                    height: 34,
                    padding: 5,
                    border: '1px solid #D9D9D9',
                    borderRadius: 5
                  }}
                >
                  {position.longitude}, {position.latitude}
                </div> */}
                            </Form.Item>
                            {/* <Amap
                width="100%"
                height="200"
                position={position}
                setPosition={setPosition}
              /> */}
                        </Col>
                        <Col span={24}>
                            <Form.Item label="营业执照" name="businessLicense">
                                <ImageUpload imageUrl={imageUrl} setImageUrl={setImageUrl}/>
                            </Form.Item>
                        </Col>
                        <Col span={24}>
                            <Form.Item label="商家简介" name="profile">
                                <Input.TextArea placeholder="请输入商家简介"/>
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </Modal>
        </>
    )
}
